package com.kb.erp.service.digi;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kb.erp.mapper.sqlServer.DigikeyMapper;
import com.kb.erp.mapper.sqlServer.TokenMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

@Service
@Slf4j
@DS("component")
public class TestController {

    private String url = "https://api.digikey.com/v1/oauth2/token";
    private String clientId ="lnGfrAAGJZMWdzRYe7eJTEn5tgEl0eKc";

    private String clientSecret ="1aUJX2eqqnh9oaja";

    private String grantType ="client_credentials";

    @Resource
    private DigikeyMapper mapper;
    @Resource
    private TokenMapper tokenMapper;




    @Async // 使用异步处理
    public CompletableFuture<List<ProductData1>> getQuoteAsync(QueryTO to) throws JsonProcessingException, ExecutionException, InterruptedException {
        // 保持原来同步方法的逻辑
        List<ProductData1> result = getQuote(to);  // 调用原有的同步方法
        return CompletableFuture.completedFuture(result);
    }


    public List<ProductData1> getQuote(QueryTO to) throws JsonProcessingException, ExecutionException, InterruptedException {
        try {
            String token = getToken(3);
            List<String> productNumbers = new ArrayList<>();
            List<ProductData1> result = new ArrayList<>();
            QueryWrapper<Digikey> wrapper = new QueryWrapper<>();
            log.info("keyword: " + to.getKeyWord());
            log.info("currency: " + to.getCurrency());
            wrapper.eq("keyword", to.getKeyWord());
            wrapper.eq("currency", to.getCurrency());

            List<Digikey> digikeyList = mapper.selectList(wrapper);

            Digikey digikey = null;
            if (!digikeyList.isEmpty()) {
                digikey = digikeyList.get(0); // 只取第一个结果
            }

            ObjectMapper objectMapper = new ObjectMapper();
            Boolean isExist = false;
            if (digikey != null) {
                log.info("系统有收录该关键字和币种");
                isExist = true;
                List<ProductData> quote = objectMapper.readValue(digikey.getJsondata(), new TypeReference<List<ProductData>>() {});
                if (quote != null && !quote.isEmpty()) {
                    for (ProductData data : quote) {
                        productNumbers.addAll(data.getProduct().getProductVariations().stream()
                                .filter(variation -> variation != null
                                        && variation.getPackageType() != null
                                        && variation.getPackageType().getName() != null
                                        && !variation.getPackageType().getName().contains("Digi-Reel"))
                                .map(ProductData.ProductVariation::getDigiKeyProductNumber)
                                .collect(Collectors.toList()));
                    }
                }

            }

            if (productNumbers.isEmpty()) {
                String jsonBody = "{"
                        + "\"KeyWord\": \"" + to.getKeyWord() + "\","
                        + "\"Currency\": \"" + to.getCurrency() + "\","
                        + "\"token\": \"" + token + "\""
                        + "}";

                // Make the HTTP request to the new endpoint
                HttpResponse response = HttpRequest.post("http://8.155.30.82:82/api/DigikeyApi/GetQuote")
                        .header("Content-Type", "application/json")
                        // Include token in the header
                        .timeout(60000)
                        .body(jsonBody)
                        .execute();


                String responseBody = response.body();
                JSONObject jsonResponse = JSONUtil.parseObj(responseBody);
                JSONArray productsArray = jsonResponse.getJSONArray("Products");

                // 如果有 ExactMatches 数据合并
                JSONArray exactMatchesArray = jsonResponse.getJSONArray("ExactMatches");
                if (exactMatchesArray != null && !exactMatchesArray.isEmpty()) {
                    productsArray.addAll(exactMatchesArray);
                }

                if(productsArray!=null){
                    for (int i = 0; i < productsArray.size(); i++) {
                        JSONObject product = productsArray.getJSONObject(i);
                        JSONArray productVariations = product.getJSONArray("ProductVariations");
                        for (int j = 0; j < productVariations.size(); j++) {
                            JSONObject variation = productVariations.getJSONObject(j);
                            JSONObject packageType = variation.getJSONObject("PackageType");
                            if (packageType != null && !packageType.getStr("Name").contains("Digi-Reel")) {
                                String digiKeyProductNumber = variation.getStr("DigiKeyProductNumber");
                                if (digiKeyProductNumber != null) {
                                    productNumbers.add(digiKeyProductNumber.replace("/", "%2F").replace("#", "%23"));
                                }
                            }
                        }
                    }
                }

            }

            // 异步获取产品详细信息
            if (!productNumbers.isEmpty()) {
                result = ProductDetailsFetcher.fetchProductDetails(productNumbers, token, to.getCurrency());
                result = filterProductData(result);
            }

            if (!result.isEmpty() && !isExist && StringUtils.isNotBlank(to.getKeyWord())) {
                log.info("系统暂时没有收录该关键字和币种");
                Digikey key = new Digikey();
                key.setId(UUID.randomUUID().toString());
                key.setCurrency(to.getCurrency());
                key.setJsondata(objectMapper.writeValueAsString(result));
                key.setKeyword(to.getKeyWord());
                mapper.insert(key);
            }

            return result;
        } catch (Exception e) {
            log.error("请求得捷关键字错误，物料为: " + to.getKeyWord(), e);
            throw new RuntimeException(e);
        }
    }



    public static List<ProductData1> filterProductData(List<ProductData1> productDataList) {
        // Step 1: Collect all digiKeyProductNumber occurrences
        Set<String> setList = new HashSet<>();
        List<ProductData1> result = new ArrayList<>();

        for (ProductData1 productData : productDataList) {
            if (productData != null && productData.getProduct() != null && productData.getProduct().getProductVariations() != null) {
                boolean isPass = false;
                for (ProductData1.ProductVariation variation : productData.getProduct().getProductVariations()) {
                    String digiKeyProductNumber = variation.getDigiKeyProductNumber();
                    if (setList.add(digiKeyProductNumber)) {
                        isPass = true;
                    }
                }
                if (isPass) {
                    result.add(productData);
                }
            }
        }
        return result;
    }


    private String getToken(Integer type){
        QueryWrapper<Token> wrapper=new QueryWrapper();
        wrapper.eq("type",type);
        Token existingToken=tokenMapper.selectOne(wrapper);

        if(existingToken!=null){
            return existingToken.getToken();
        }else{
            return updateToken();
        }



    }


    public String updateToken() {
        try {
            String postData = "client_id=" + URLEncoder.encode(clientId, "UTF-8") +
                    "&client_secret=" + URLEncoder.encode(clientSecret, "UTF-8") +
                    "&grant_type=" + URLEncoder.encode(grantType, "UTF-8");

            // 发送POST请求，使用HttpUtil
            String responseBody = HttpUtil.post(url, postData);

            // 解析 JSON
            JSONObject jsonObject = new JSONObject(responseBody);
            Date currentDate = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String formattedDate = dateFormat.format(currentDate);
            log.info(formattedDate + " token结果为: " + jsonObject);
            // 提取 access_token 和 expires_in
            String token = jsonObject.getStr("access_token");
            Long time = jsonObject.getLong("expires_in");


            if(StringUtils.isNotBlank(token)&&time!=null){
                QueryWrapper<Token> wrapper=new QueryWrapper();
                wrapper.eq("type",3);
                Token existingToken=tokenMapper.selectOne(wrapper);

                if (existingToken == null) {
                    Token newToken = new Token();
                    newToken.setToken(token);
                    newToken.setExpireTime(time);
                    newToken.setType(3);
                    tokenMapper.insert(newToken);
                } else {
                    existingToken.setExpireTime(time);
                    existingToken.setToken(token);
                    tokenMapper.updateById(existingToken);
                }
                return token;
            }

            return null;
        } catch (HttpException e) {
            log.error(String.valueOf(e));
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

    }



    @ResponseBody
    public CompletableFuture<ApiResponse> getQuoteResult(@RequestBody QueryTO to) throws JsonProcessingException, ExecutionException, InterruptedException {
        // 调用异步方法
        return getQuoteAsync(to)
                .thenApply(quote -> ApiResponse.successCount(quote, quote.size()));
    }

}
